<?php

namespace app\admin\service;

use app\model\AdminMenu;
use app\model\AdminRule;
// use think\facade\Session;
use think\facade\Cache;

class RuleService
{
    private $adminRuleModel;
    private $adminMenuModel;

    public function __construct()
    {
        $this->adminRuleModel = new AdminRule();
        $this->adminMenuModel = new AdminMenu();
    }

    // 获取菜单数据
    public function getMenuData($userInfo)
    {
        $userId = $userInfo['user_id'];
        $ruleId = $userInfo['rule_id'];

        if (empty($ruleId) || empty($userId)) {
            return redirect(url('admin/login/index'));
        }

        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.admin.admin_menu_data');
        $expire = config('redis_key.admin.admin_menu_expire');
        $redis->select(3);

        $adminRuleIds = config('enum.admin_rule_ids');

        $menuData = [];
        if (in_array($ruleId, $adminRuleIds)) {
            $menuData = $this->adminMenuModel->getAllData();
        } else {
            $ruleData = $this->adminRuleModel->getDataById($ruleId);
            $menuIds = explode(',', $ruleData['menu_ids']);
            $menuData = $this->adminMenuModel->getDataByWhere(['id' => $menuIds]);
        }

        $childrenData = $authUrl = [];
        foreach ($menuData as $item) {
            if ($item['pid'] && !$item['hide']) {
                $childrenData[$item['pid']][] = $item;
            }

            if ($item['path']) {
                $path = strtolower(substr($item['path'], 1));
                $currentEncode = mb_detect_encoding($path, ['ASCII', 'GB2312', 'GBK', 'BIG5', 'UTF-8']);
                $path = mb_convert_encoding($path, 'UTF-8', $currentEncode);
                $authUrl[] = $path;
            }
        }

        $menu = [];
        foreach ($menuData as $item) {
            if (!$item['hide'] && !$item['pid']) {
                $item['children_menu_data'] = !empty($childrenData[$item['id']]) ? $childrenData[$item['id']] : [];
                $menu[] = $item;
            }
        }

        $bool = $redis->set($key . $ruleId, json_encode($authUrl), $expire);
        if (!$bool) {
            return [];
        }

        return $menu;
    }

    // 添加/编辑角色
    public function edit($params)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }

        $id = $this->adminRuleModel->edit($params);
        return $id;
    }

    // 角色列表
    public function getList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $where = [];

        $data = $this->adminRuleModel->getPagingData($where, $page, $limit);

        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['menu_ids'] = explode(',', $item['menu_ids']);
            }
        }

        return $data;
    }

    // 角色删除
    public function delete($id)
    {
        $data = $this->adminRuleModel->destroy($id);

        if (!$data) {
            return ['message' => Error::DELETE_FAIL];
        }
        return [];
    }

    // 获取角色详情
    public function getRuleDetail($id)
    {
        $data = $this->adminRuleModel->getDataById($id, 'id, name, menu_ids');
        $data['menu_ids'] = explode(',', $data['menu_ids']);
        return $data;
    }

    // 获取角色下拉列表
    public function getRuleSelectList()
    {
        $data = $this->adminRuleModel->getDataByWhere();
        return $data;
    }
}